package http;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class MyHttpServer2 {
    ServerSocket serverSocket;

    Function<String, String> handler;

    public MyHttpServer2(Function<String, String> handler) {
        this.handler = handler;
    }

    public void listen(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        for (; ; ) {
            accept();
        }
    }

    public void accept() throws IOException {
        Socket socket = serverSocket.accept();
        new Thread(() -> {
            try {
                handler(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void handler(Socket socket) throws IOException {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                        new DataInputStream(socket.getInputStream())));
        String line = "";
        StringBuilder requestBuilder = new StringBuilder();
        while ((line = reader.readLine()) != null && line.length() > 0) {
            requestBuilder.append(line).append("\n");
        }
        System.out.println(requestBuilder.toString());
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(
                        new DataOutputStream(socket.getOutputStream())));
        writer.write(handler.apply(requestBuilder.toString()));
        writer.flush();
        socket.close();
    }


    public static void main(String[] args) throws IOException {
        MyHttpServer2 myHttpServer1 = new MyHttpServer2((req) -> {
            return "HTTP/1.1 200 ok\n\nHello World!\n";
        });
        myHttpServer1.listen(8001);
    }
}
